package com.greydawn.PrototypePattern;

import java.util.HashMap;

/**
 * @Author: zhongwr
 * @Create: 2021/12/12 15:07
 * @Version 1.0
 * @Description: 原型模式测试
 * 原型模式，用原型实例指定创建对象的种类，并且通过拷贝这些原型创建新的对象
 * 原型模式就是从一个对象再创建另一个可定制的对象，而且不需要知道任何创建细节
 */
public class PrototypeTest {

    private static HashMap<String, People> peopleHashMap = new HashMap<>();

    public static void main(String[] args) {
        loadChache();

        People p1 = getByName("no1");
        People p2 = getByName("no2");

        System.out.println(p1.toString());
        System.out.println(p2.toString());
        p1.doSomething();
        p2.doSomething();

        // 验证浅拷贝 即基本数据类型拷贝值，引用数据类型拷贝引用，
        // 所以拷贝出来的对象和原对象引用同一个内部对象，更改这个内部对象会导致原对象和拷贝对象都发生改变
        Address add1 = new Address("皇后大道东");
        PeopleNo1 peopleNo1 = new PeopleNo1();
        peopleNo1.setName("皇后");
        peopleNo1.setAddress(add1);

        People copy = (People) peopleNo1.clone();
        System.out.println(peopleNo1);
        System.out.println(copy);
        System.out.println("更改Address");
        add1.setStr("皇后大道西了");
        System.out.println(peopleNo1);
        System.out.println(copy);

    }

    public static People getByName(String name) {
        People people = peopleHashMap.get(name);
        return (People) people.clone();
    }

    // 模拟从数据库读取数据生成对象，并保存在HashMap里面
    private static void loadChache() {
        PeopleNo1 no1 = new PeopleNo1();
        no1.setName("no1");
        peopleHashMap.put("no1", no1);

        PeopleNo2 no2 = new PeopleNo2();
        no2.setName("no2");
        peopleHashMap.put("no2", no2);

    }

}
